package com.oocl.client.ui.impl;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

import com.oocl.client.callback.ProtocolFinishProcessCallback;
import com.oocl.client.callback.WindowCloseCallback;
import com.oocl.client.process.ProtocolReceiver;
import com.oocl.client.process.ProtocolSender;
import com.oocl.client.ui.BaseFrame;
import com.oocl.client.ui.IChatOperator;
import com.oocl.client.vibration.ScreenVibrator;
import com.oocl.qq.protocol.Action;
import com.oocl.qq.protocol.Protocol;

public class ChatFrame extends BaseFrame implements ActionListener, IChatOperator {
	// //组件
	private JTextArea chatTa;
	private JTextArea friendsTa;
	private JTextField sendTf;
	private JButton sendBtn;
	private JButton shakeBtn;
	private JButton btnToAll;
	private JPanel rightPanel;
	private JScrollPane scrollPane;
	private JScrollBar scrollBar;

	// /常量

	private final String EVERYONE = "所有人";
	private final String SHAKE_ME = "振动了我一下";
	private final String SAY = "说： ";
	private final int BUTTON_HEIGHT = 3;
	private final int BUTTON_WIDTH = 10;

	/// 属性
	private String userName;
	private String toWhom = null;
	private String userListData;

	/// socket 的对象流
	private ObjectInputStream objectIn;
	private ObjectOutputStream objectOut;

	/// 窗口关闭的监听器
	private WindowCloseCallback windowCloseCallback;
	private ScreenVibrator screenVibrator;
	///协议发送接口
	private ProtocolSender protocolSender;
		
		

	// //数据
	private List<String> userList;

	public ChatFrame(String userName, List<String> userList) {
		super();

		screenVibrator = new ScreenVibrator();
		this.userList = userList;
		this.userName = userName;
		if (this.userName == null || this.userName.length() == 0) {
			System.out.println("用户名不能为空，您的登录操作失败");
		}
		this.toWhom = null;
		if (this.userList == null)
			this.userList = new ArrayList<String>();
		if (this.userList!=null && this.userName != null)
			this.userList.remove(userName);
		refreshData();
	}

	public void setWindowCloseCallback(WindowCloseCallback windowCloseCallback) {
		this.windowCloseCallback = windowCloseCallback;
	}

	public void setProtocolSender(ProtocolSender protocolSender){
		this.protocolSender = protocolSender;
	}
	
	@Override
	protected void initFrame() {
		this.setSize(500, 300);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				// //要退出了
				Protocol p = new Protocol(Action.Logout, userName);
				protocolSender.sendProtocol(p);
				if (windowCloseCallback != null)
					windowCloseCallback.closeWindow();
			}
		});
		this.setLocationRelativeTo(null);
	}

	@Override
	protected void init() {
		this.setLayout(new BorderLayout());
		JPanel panLeft = new JPanel(new BorderLayout());
		JPanel panRight = new JPanel(new BorderLayout());
		this.rightPanel = panRight;
		JPanel panLeftBottom = new JPanel(new BorderLayout());
		JPanel panBtnGroup = new JPanel(new BorderLayout());
		chatTa = new JTextArea(10, 20);

		friendsTa = new JTextArea(10, 12);

		sendTf = new JTextField();
		sendBtn = new JButton("send");
		shakeBtn = new JButton("shake");

		sendTf.setFont(new Font("宋体", Font.BOLD, 12));
		sendTf.setForeground(Color.red);

		chatTa.setFont(new Font("宋体", Font.BOLD, 12));
		chatTa.setForeground(Color.blue);
		chatTa.setSize(500, 400);
		chatTa.setWrapStyleWord(true);
		chatTa.setLineWrap(true);

		friendsTa.setLayout(new GridLayout(0, 1));
		friendsTa.setSize(220, 0);
		
		JScrollPane friendScrollPane = new JScrollPane();
		friendScrollPane.setViewportView(friendsTa);
		friendScrollPane.setSize(BUTTON_WIDTH*2, 280);
		panRight.add(friendScrollPane, BorderLayout.EAST);

		
		this.scrollPane = new JScrollPane(chatTa);
		
		this.scrollBar = this.scrollPane.getVerticalScrollBar();
		panLeft.add(this.scrollPane, BorderLayout.CENTER);
		panLeft.add(panLeftBottom, BorderLayout.SOUTH);
		panRight.setBorder(new LineBorder(Color.red));
		////用一个空的Label 卡位置
		panRight.add(new JLabel(),BorderLayout.CENTER);
		
		
		this.add(panLeft, BorderLayout.CENTER);
		this.add(panRight, BorderLayout.EAST);
		panBtnGroup.add(shakeBtn, BorderLayout.NORTH);
		panBtnGroup.add(sendBtn, BorderLayout.SOUTH);
		panLeftBottom.add(sendTf, BorderLayout.CENTER);
		panLeftBottom.add(panBtnGroup, BorderLayout.EAST);

		this.btnToAll = new JButton(EVERYONE);
	}

	@Override
	protected void addEvent() {
		sendBtn.addActionListener(this);
		shakeBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// /震动消息发送

				// /只是群发
				Protocol p = null;
				if (toWhom == null) {
					p = new Protocol(Action.Shake, userName, null, null, System.currentTimeMillis());

				} else {
					p = new Protocol(Action.Shake, userName, toWhom, null, System.currentTimeMillis());

				}
				protocolSender.sendProtocol(p);
			}
		});

		this.btnToAll.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// /设置当前的to 为 null
				toWhom = null;
				System.out.println(userName + "选定了聊天对象： 所有人");
				refreshScreen();
			}

		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String content = sendTf.getText().trim();
		if (content == null || content.length() == 0)
			return;

		System.out.println(content);
		long curTime = System.currentTimeMillis();
		DateFormat format = new SimpleDateFormat("HH:mm");
		this.appendChatLine("[" + format.format(curTime) + "] 我：" + content);

		// /并且，构造一条消息，发送给服务器
		Protocol sendMsg = new Protocol(Action.Chat, this.userName, this.toWhom, content, curTime);
		this.protocolSender.sendProtocol(sendMsg);
	}

	//// 添加一句聊天
	private void appendChatLine(String chatMsg) {
		this.chatTa.append(chatMsg + "\n");
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		scrollBar.setValue(scrollBar.getMaximum());/// 让滚动条自动下滚
		scrollBar.revalidate();
	}

	// /更新数据
	private void refreshData() {
		// /清空
		this.friendsTa.removeAll();
		// this.friendsTa.revalidate();

		// /根据用户名列表，创建Button
		int len;
		if (this.userList == null || this.userList.size() == 0)
			len = 0;
		else
			len = this.userList.size();

		this.friendsTa.setRows(BUTTON_HEIGHT * (len + 1));
		this.friendsTa.setSize(10, BUTTON_HEIGHT * (len + 1));
		this.friendsTa.add(this.btnToAll);

		if (len > 0) {
			int i = 0;
			for (String item : userList) {
				final JButton btn = new JButton(item);
				btn.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
				btn.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						toWhom = btn.getText();
						System.out.println(userName + "选定了聊天对象： " + toWhom);
						refreshScreen();
					}
				});
				// this.btnUserList.add(btn);
				this.friendsTa.add(btn);
			}
		}
		// /刷新panel
		this.friendsTa.revalidate();
		this.rightPanel.revalidate();
		refreshScreen();
	}

	// 刷新整个视图
	private void refreshScreen() {
		// /toWhom 找一下 userList ，看人还在不在，不在，就为null
		if (toWhom != null)
			if (this.userList==null ||!this.userList.contains(toWhom))
				toWhom = null;

		// //更新标题
		this.setTitle(this.userName + " 与  " + ((this.toWhom == null) ? (EVERYONE) : this.toWhom) + " 的聊天");
	}

	@Override
	public void shake(String fromWhom, String time) {
		this.appendChatLine("[" + time + "] " + fromWhom + SHAKE_ME);
		this.screenVibrator.startVibrate(this);
	}

	@Override
	public void receiveMsg(String fromWhom, String msg, String time) {
		if(fromWhom!=null)
		this.appendChatLine("[" + time + "] " + fromWhom + SAY + msg);
		else if(msg!=null)
			this.appendChatLine("[" + time + "] " + msg);
	}

	@Override
	public void updateOnlineUsers(List<String> onlineUsers) {
		System.out.println("在线用户列表更新");
		// /解析新的用户列表
		this.userList = onlineUsers;
		refreshData();
	}

	@Override
	protected void sendProtocol(Protocol protocol) {
		this.protocolSender.sendProtocol(protocol);
	}

}
